<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */
namespace App\Controller\User;

use App\Controller\AppBaseController;
use App\Model\ActJoin;
use App\Model\Collect;
use App\Model\IntegralLog;
use App\Model\MultiCollect;
use App\Model\MultiLearn;
use App\Model\MultiZan;
use App\Model\Notify;
use App\Model\Party;
use App\Model\User;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\WxApiAuth;

#[Controller(prefix: 'user')]
#[Middleware(WxApiAuth::class)]
class UserController extends AppBaseController
{
    /**
     * 获取用户信息
     * @return object
     */
    #[RequestMapping(path:'userInfo',methods: 'get')]
    public function userInfo(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $where['status'] = 1;
            $where['id'] = $_user->id;
            $userInfo = User::with(['party'=>function($query){
                    $query->selectRaw('id,name,integral,integral_active')->first();
                 }])
                ->where($where)
                ->selectRaw('id,nickname,avatar,auth_name,auth_key,party_id,user_type,integral,department,political_birthday')->first();
            if(empty($userInfo)){
                $this->session->set('api_user', null);
                $this->session->save();
            }
            $userInfo->is_birthday = 0;
            if($userInfo->political_birthday){
                $today = date('Y-m-d',time());
                $birthday = date('Y-m-d',strtotime($userInfo->political_birthday));
                if($today==$birthday) $userInfo->is_birthday = 1;
            }
            return $this->reMsg->re(1,'success',$userInfo);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 用户积分排行
     * @return object
     */
    #[RequestMapping(path: 'userIntegralRank',methods: 'get')]
    public function userIntegralRank() :object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $list = User::whereNotNull('auth_time')->selectRaw('id,nickname,avatar,auth_name,integral,integral_time')
                ->orderByDesc('integral')
                ->orderBy('integral_time')
                ->offset($offset)
                ->limit($limit)
                ->get();
            $next = 0;
            $integral = 0;
            $rank = 0;
            if($list->isNotEmpty()){
                if(count($list)>$limit) $next = 1;
                $userInfo = User::where('id',$_user->id)->selectRaw('id,integral,integral_time')->first();
                if($userInfo){
                    $integral = $userInfo->integral;
                    $rank = User::where('integral','>',$integral)
                        ->orderBy('integral_time')
                        ->count();
                    $rank++;
                }
            }
            return $this->reMsg->re(1,'success',['list'=>$list,'integral'=>$integral,'rank'=>$rank,'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 支部积分排行
     * @return object
     */
    #[RequestMapping(path: 'partyIntegralRank',methods: 'get')]
    public function partyIntegralRank() :object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 100);
            $offset = ($page - 1) * $limit;

            $list = Party::selectRaw('id,name,integral,integral_time')
                ->orderByDesc('integral')
                ->orderBy('integral_time')
                ->offset($offset)
                ->limit($limit)
                ->get();
            $next = 0;
            $integral = 0;
            $rank = 0;
            if($list->isNotEmpty()){
                if(count($list)>$limit) $next = 1;
                foreach ($list as $key=>$value){
                    $rank++;
                    if($_user->party_id==$value->id){
                        $integral = $value->integral;
                        break;
                    }
                }
            }
            return $this->reMsg->re(1,'success',['list'=>$list,'integral'=>$integral,'rank'=>$rank,'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 用户积分日志
     * @return object
     */
    #[RequestMapping(path: 'userIntegralLog',methods: 'get')]
    public function userIntegralLog() :object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $list = IntegralLog::where('uid',$_user->id)
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();
            $next = 0;
            if($list->isNotEmpty()){
                if(count($list)>$limit) $next = 1;
            }
            //用户积分
            $integral = 0;
            $userInfo = User::where('id',$_user->id)->selectRaw('id,integral')->first();
            if($userInfo){
                $integral = $userInfo->integral;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'integral'=>$integral,'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 清除用户信息
     * @param int $type  1:清除授权信息  2：清除操作信息 3：清除所有信息
     * @return object
     */
    #[RequestMapping(path:'clearCache/{type}',methods: 'get')]
    public function clearCache(int $type=1):object
    {
        //验证用户信息
        $checkInfo = $this->checkUser();
        if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
        $_user = $checkInfo['data'];

        if($type==1){}
        if($type==2){
            $userInfo = User::getUserInfoByUserId($_user->id);
            $userInfo->openid = null;
            $userInfo->nickname = null;
            $userInfo->avatar = null;
            $userInfo->auth_time = null;
            $userInfo->integral = null;
            $userInfo->integral_time = null;
            $userInfo->save();
        }
        if($type==3){}
        $this->session->set('api_user', null);
        $this->session->save();
        return $this->reMsg->re(1,'已清除');
    }



    /**
     * 用户列表
     * @return object
     */
    #[RequestMapping(path:'userList',methods: 'get')]
    public function userList(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where = [];
            $where['status'] = 1;
            $list = User::where($where)
                ->selectRaw('id,nickname,avatar,auth_name')
                ->offset($offset)
                ->limit($limit)
                ->get();
            $next = 0;
            if($list->isNotEmpty()){
                if(count($list) >= $limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 更新用户信息
     * @param int $uid
     * @return object
     */
    #[RequestMapping(path:'userInfoUpdate/{uid}',methods: 'post,get')]
    public function userInfoUpdate(int $uid): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $data = $this->request->all();

            //虚拟数据
//            if(empty($data)){
//                $data['auth_name'] = 'ceshi1';
//                $data['auth_key'] = '18961855604';
//                $data['department'] = 'j技术部';
//                $data['party_id'] = 1;
//                $data['political_birthday']='2024-10-01';
//            }
            //虚拟数据

            if( !isset($data['auth_name']) || $data['auth_name']==null
                || !isset($data['auth_key']) || $data['auth_key']==null
                || !isset($data['party_id']) || !is_numeric($data['party_id'])
                || !isset($data['department']) || $data['department']==null
            ) return $this->reMsg->re(10007);

            $info = User::where('id',$uid)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            $info->auth_name = $data['auth_name'];
            $info->auth_key = $data['auth_key'];
            $info->department = $data['department'];
            if(isset($data['political_birthday']) || $data['political_birthday']){
                $info->political_birthday = $data['political_birthday'];
            }
            $info->save();

            //修改缓存数据
            $_user->party_id = $info->party_id;
            $this->session->set('api_user',$_user);
            $this->session->save();

            //加积分
            $params = [
                'type'=> 10, //积分类型 type 1:学习 2:评论 4:支部活动点赞 5:答题 6:报名 7:抽奖 8:签到 9:问卷 10:支部信息更新
                'action' => 1, //action 1:加积分 2:减积分
                'uid' => $_user->id,  //用户id
                'party_id' => $_user->party_id  //支部id
            ];
            $this->makeIntegralLog($params);
            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 用户查询
     * @return object
     */
    #[RequestMapping(path:'userSearch',methods: 'get')]
    public function userSearch(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $name = $this->request->input('name',null);
            if(empty($name)) return $this->reMsg->re(10007);
            $where[] = ['auth_name','like','%'.$name.'%'];
            $where['status'] = 1;
            $list = User::with(['party'=>function($query){
                    $query->selectRaw('id,name')->first();
                }])->where($where)
                ->whereNotNull('auth_time')
                ->selectRaw('id,nickname,avatar,auth_name,party_id')
                ->get();
            return $this->reMsg->re(1,'success',['list'=>$list]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 积分排行
     * @return object
     */
    #[RequestMapping(path:'integralRankList',methods: 'get')]
    public function integralRankList(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where = [];
            $where['status'] = 1;
            $list = User::where($where)
                ->selectRaw('id,nickname,avatar,auth_name,integral,updated_at')
                ->where('integral','>',0)
                ->whereNotNull('auth_time')
                ->orderByDesc('integral')
                ->orderByDesc('integral_time')
                ->offset($offset)
                ->limit($limit)
                ->get();
            $next = 0;
            if($list->isNotEmpty()){
                if(count($list)>= $limit) $next = 1;
            }

            //获取用户此刻的总金额
            $integral = 0;
            $rank = 0;
            if($page==1){
                $userIntegral = User::where('id',$_user->id)->selectRaw('id,integral,integral_time')->first();
                $integral = intval($userIntegral->integral);
                //查询排名
                $rankList = User::where('integral','>=',$integral)
                    ->selectRaw('id,integral,integral_time')
                    ->whereNotNull('auth_time')
                    ->orderByDesc('integral')
                    ->orderBy('integral_time')
                    ->get();
                if($rankList->isNotEmpty()){
                    foreach ($rankList as $value){
                        $rank++;
                        if($value->id==$_user->id){
                            break;
                        }
                    }
                }
            }
            return $this->reMsg->re(1,'success',[
                'list' => $list,
                'next' => $next,
                'integral'=>$integral,
                'rank'=>$rank
            ]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 积分日志排行
     * @return object
     */
    #[RequestMapping(path:'integralLogList',methods: 'get')]
    public function integralLogList(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $list = IntegralLog::where('uid',$_user->id)
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $next = 0;
            if($list->isNotEmpty()){
                if(count($list)>= $limit) $next = 1;
            }
            //获取用户此刻的总金额
            $integral = 0;
            if($page==1){
                $userIntegral = User::where('id',$_user->id)->selectRaw('id,integral')->first();
                $integral = $userIntegral->integral;
            }
            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next, 'integral'=>$integral]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 用户数据分析
     * @return object
     */
    #[RequestMapping(path:'dataStatistics',methods: 'get')]
    public function dataStatistics(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            //活动参与次数
            $where['uid'] = $_user->id;

            //报名打卡数量
            $actJoinCount = ActJoin::where($where)->count();
            //答题次数
//            $actAnswerCount = ActAnswerJoin::where($where)->count();
            //打卡次数
//            $actPrizeCount = ActPrizeJoin::where($where)->count();
//            $actJoinCount = $actJoinCount + $actAnswerCount + $actPrizeCount;

            //收藏总数
            $multiWhere['uid'] = $_user->id;
            $multiWhere['status'] = 1;
            $collectCount = MultiCollect::where($multiWhere)->count();
            //点赞总数
            $zan_count = MultiZan::where($multiWhere)->count();

            //学习次数
            $learn_count = MultiLearn::where($where)->count();

            //消息总数
            $notifyCount = Notify::where($where)->count();



            return $this->reMsg->re(1,'success',[
                'act_join_count' => $actJoinCount,
                'collect_count' => $collectCount,
                'zan_count'=>$zan_count,
                'learn_count' => $learn_count,
                'notify_count' => $notifyCount,
            ]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }

    /**
     * 用户的参与互动记录
     * @return object
     */
    #[RequestMapping(path:'actJoinList',methods: 'get')]
    public function actJoinList(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['uid'] = $_user->id;

            $list = ActJoin::with(['act'=>function($query){
                    $query->selectRaw('id,title,photo,created_at')->first();
                }])
                ->where($where)
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $next = 0;
            if($list->isNotEmpty()){
                if(count($list) >= $limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 我的学习
     * @return object
     */
    #[RequestMapping(path:'multiLearnList',methods: 'get')]
    public function multiLearnList(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['uid'] = $_user->id;
            $list = MultiLearn::where($where)
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();
            $next = 0;
            if($list->isNotEmpty()){
                if(count($list) >= $limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 我的收藏（最新）
     * @return object
     */
    #[RequestMapping(path:'multiCollectList',methods: 'get')]
    public function multiCollectList(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['status'] = 1;
            $where['uid'] = $_user->id;

            $list = MultiCollect::where($where)
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();
            $next = 0;
            if($list->isNotEmpty()){
                if(count($list) >= $limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 我的点赞（最新）
     * @return object
     */
    #[RequestMapping(path:'multiZanList',methods: 'get')]
    public function multiZanList(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['status'] = 1;
            $where['uid'] = $_user->id;

            $list = MultiZan::where($where)
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();
            $next = 0;
            if($list->isNotEmpty()){
                if(count($list) >= $limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /** next old api */

    /**
     * 我的收藏
     * @return object
     */
    #[RequestMapping(path:'collectList',methods: 'get')]
    public function collectList(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['status'] = 1;
            $where['uid'] = $_user->id;

            $list = Collect::where($where)
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $next = 0;
            if($list->isNotEmpty()){
                if(count($list) >= $limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }





}